const Service = require("egg").Service;
const { timestamp } = require("../utils/tools");

class UserService extends Service {
  // 登录
  async login(name, password, token) {
    let result = {};
    const last_time = timestamp();
    const info = await this.app.mysql.get("user", {
      name,
      password,
    });
    const login_user_result = await this.app.mysql.get("login_user", {
      name,
      password,
    });
    if (!info) {
      result = {
        type: "fail",
        message: "用户名或者密码错误",
      };
    } else {
      result = await this.app.mysql.insert("login_user", {
        name,
        password,
        token,
        last_time,
        user_id: info?.id,
      });
      result.type = "success";
    }

    if(login_user_result){
      await this.app.mysql.delete("login_user", {
        name, password
      });
      result = await this.app.mysql.insert("login_user", {
        name,
        password,
        token,
        last_time,
        user_id: info?.id,
      });
      result.type = "success";
    }

    return result;
  }

  // 退出登录
  async logout(token) {
    const result = await this.app.mysql.delete("login_user", {
      token,
    });
    return result;
  }

  // 用户信息
  async info(id = "", token = "") {
    let result = [];
    let uid = "";
    if (id) {
      uid = id;
    } else {
      const { user_id } = await this.app.mysql.get("login_user", {
        token,
      });
      uid = user_id;
    }
    result = await this.app.mysql.get("user", {
      id: uid,
    });
    const user_role = await this.app.mysql.select("user_role", {
      where: {
        uid,
      },
    });
    const roles_id = user_role.map((item) => item.rid).join();
    const result2 = await this.app.mysql.query(
      `select * from role where id in(${roles_id})`
    );
    const btns = [];
    const routes = [];

    result2.forEach((item) => {
      item.btns?.split(",").forEach((child) => {
        if (child !== "" && !btns.includes(child)) {
          btns.push(child);
        }
      });
      item.routes?.split(",").forEach((child) => {
        if (child !== "" && !routes.includes(child)) {
          routes.push(child);
        }
      });
    });
    const { password = "", ...rest } = result;
    return {
      ...rest,
      roles: result.roles?.split(),
      btns,
      routes,
    };
  }

  // 用户信息
  async info_by_name(name) {
    const result = await this.app.mysql.get("user", {
      name,
    });
    return result;
  }

  // 新增用户
  async add(name, password) {
    const result = await this.app.mysql.insert("user", {
      name,
      password,
      create_time: Date.now(),
    });
    return result;
  }

  // 修改用户
  async edit(id, name) {
    const result = await this.app.mysql.update("user", {
      id,
      name,
      update_time: Date.now(),
    });
    return result;
  }

  // 查询用户
  async list({ keyword = "", page = 1, page_size = 10, order = "id_desc" }) {
    const [columns, mode] = order.split("_");
    const offset = (page - 1) * page_size || 0;
    const size = parseInt(page_size);
    const data = await this.app.mysql.query(
      "select id,name,roles,roles_id, create_time, update_time from user where name like ? order by ? ? limit ?, ? ;",
      [`%${keyword}%`, columns, mode, offset, size]
    );
    const total = await this.app.mysql.count("user");
    return {
      data,
      total,
    };
  }

  // 删除用户
  async delete({ delete_id }) {
    const ids = delete_id.join(",");
    const result = await this.app.mysql.query(
      `delete from user where id in (${ids});`
    );
    return result;
  }

  // 用户分配角色
  async add_role({ id, roles = [] }) {
    if (roles.length === 0) return true;
    const role_result = await this.app.mysql.select("role", {
      where: {
        id: roles,
      },
    });
    const roles_id = roles.join();
    const roles_values = roles.map((item) => `(${id}, ${item})`);
    const user_roles = role_result.map((item) => item.role_name).join();
    await this.app.mysql.query(
      `insert into user_role(uid, rid) values ${roles_values}`
    );
    const result = await this.app.mysql.update("user", {
      id,
      roles: user_roles,
      roles_id,
    });

    return result;
  }
}

module.exports = UserService;
